package models

import (
	"github.com/nfnt/resize"
	"os"
	"path/filepath"
	"image"
	"image/jpeg"
	"log"
	"errors"
	"runtime"
	"strings"
	"os/exec"
	"strconv"
	//"bytes"
)

var (
	resizer_app string

)

func ResizeInit() error {
	log.Println("current os:", runtime.GOOS)
	path, err := exec.LookPath("vipsthumbnail")
	if err != nil {
		if strings.Contains(runtime.GOOS, "win") {
			pwd, _ := os.Getwd()
			path = pwd + `\bins\thumbgen\win32\vipsthumbnail`
		} else {
			log.Fatal("Need vipsthumbnail and libvips >= 7.30 to generate thumbnail.")
		}
	}
	log.Println("tool path: ", path)
	resizer_app = path
	
	return nil
}

func ResizeFill(root string, dirs []Imgdir) error {

	for _, dir := range dirs {
		for _, img := range dir.Imgs {
			log.Println("ResizeFill : ", img)
			ResizeImgobj(root, dir.Path, img)
		}
	}

	return nil
}

func ResizeImgobj(root string, path string, img *Imgobj) error {
	var tpath []string = make([]string, 0, 2)
	var size  []image.Point = make([]image.Point, 0, 2)

	dirpath := path[len(root):]
	if img.Thumb.Path == "" {
		img.Thumb.Path = root + THUMB_DIR + dirpath + img.Name
	}
	img.Thumb.Size = image.Point{100, 0}
	_, err := os.Stat(img.Thumb.Path)
	if os.IsNotExist(err) {
		tpath = append(tpath, img.Thumb.Path)
		size = append(size, img.Thumb.Size) 
	}

	if img.Preview.Path == "" {
		img.Preview.Path = root + PREVIEW_DIR + dirpath + img.Name
	}
	img.Preview.Size = image.Point{600, 0}
	_, err = os.Stat(img.Preview.Path)
	if os.IsNotExist(err) {
		tpath = append(tpath, img.Preview.Path)
		size = append(size, img.Preview.Size) 
	}

	if len(tpath) > 0 {
		_, err := ResizeImg(path + img.Name, tpath, size)
		if err != nil {
			log.Println("ResizeImg: ", err)
			return err
		}
		img.Thumb.Stats = Done
		img.Preview.Stats = Done
	}
	return nil
}

func ResizeImg(spath string, tpath []string, size []image.Point) (int, error) {
	if len(tpath) != len(size) {
		log.Println("GetImgThumb: ", tpath, size)
		return 0, errors.New("GetImgThumb length unsafe")
	}

	cnt := 0
	for i, tgt := range tpath {
		log.Println("+++", spath, tgt)
		_, err := os.Stat(tgt)
		if err != nil {
			if !os.IsNotExist(err) {
				log.Println(err)
				continue
			}
			// 创建文件夹
			os.MkdirAll(filepath.Dir(tgt), 0755)
			log.Println("=== ", tgt)
			cmd := exec.Command(resizer_app, spath, "-o", tgt, "-s", strconv.Itoa(size[i].X))
			err := cmd.Run()
			if err != nil {
				log.Println("run err:", spath, tgt, err)
			}
			cnt++
		}
	}

	return cnt, nil
}

func ResizeImgInGo(spath string, tpath []string, size []image.Point) (int, error) {

	if len(tpath) != len(size) {
		log.Println("GetImgThumb: ", tpath, size)
		return 0, errors.New("GetImgThumb length unsafe")
	}

	file, err := os.Open(spath)
	if err != nil {
		return 0, err
	}
	img, err := jpeg.Decode(file)
	if err != nil {
		log.Println(err)
		return 0, err
	}
	file.Close()

	cnt := 0
	for i, tgt := range tpath {
		_, err := os.Stat(tgt)
		if err != nil {
			if !os.IsNotExist(err) {
				log.Println(err)
				continue
			}
			// 创建文件夹
			os.MkdirAll(filepath.Dir(tgt), 0755)

			m := resize.Resize(uint(size[i].X), uint(size[i].Y), img, resize.NearestNeighbor)

			out, err := os.Create(tgt)
			if err != nil {
				log.Println(err)
				continue
			}

			// write new image to file
			jpeg.Encode(out, m, nil)
			out.Close()
			cnt++
		}
	}
	return cnt, nil
}




















